<?php
declare(strict_types=1);

namespace App\Model;

use Carbon\Carbon;

/**
 * @property int $id
 * @property string $name
 * @property Carbon $created_at
 * @property Carbon $updated_at
 */
class ContentTag extends MyBaseModel
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'content_tag';
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['name'];
    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'id' => 'integer',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
    ];

    public static function getIdsByNames(string $names): array
    {
        $names = str_replace('，', ',', trim($names));
        $names = explode(',', $names);
        $idArr = [];
        foreach ($names as $name) {
            $name = trim($name);
            if (empty($name)) {
                continue;
            }
            /* @var ContentTag $model */
            $model = self::firstOrCreate(['name' => $name]);
            $model && array_push($idArr, $model->id);
        }
        return $idArr;
    }

    public static function getNamesByIds(?string $ids): array
    {
        if (is_null($ids)) {
            return [];
        }
        $ids = str_replace('，', ',', trim($ids));
        $ids = explode(',', $ids);
        $idArr = [];
        foreach ($ids as $id) {
            $id = intval($id);
            $id > 0 && array_push($idArr, $id);
        }
        if (!$idArr) {
            return [];
        }
        $models = self::findManyFromCache($idArr);
        $namesArr = [];
        /* @var ContentTag $model */
        foreach ($models as $model) {
            array_push($namesArr, $model->name);
        }
        return $namesArr;
    }
}
